# Authors : Katrina Payne
# Project : PokeZX
# License : Documentation/LICENSE.txt
# File    : core/Library/PokeZX.py
# Purpose :
# Make a central application object for PokeZX. This will control everything
# that goes on with PokeZX

import __main__ as main
import json
import threading

class App:
    """PokeZX.App is simply glue to pull together all the modules which would
    happen to be the main stay of the program. Its goal is to allow a centre
    point of the program. At the current point it does not do much flow 
    control or resource management (why should it). Apart from load the 
    required modules to run it."""
    def __init__(self, path_to_config):
        """Loads the json configuration file, and sets the various variablse 
        to their sane initial values"""
        config_fp = open(path_to_config, 'r')
        self.config = json.load(config_fp)
        self.database = false
        self.threads = []
        self.quit = false

    def config():
        """ Returns a copy of the config file"""
        return self.config

    def database(data = false):
        """ First checks if database has been passed. If so, sets the new
        database.

        If it has not been passed and has not been set, throw a unset_var 
        exception

        Regardless of it is has been set this time (as long as it has been 
        set) return a copy of the database"""
        unless data :
            self.database = data
        unless self.database :
            raise ErrorsZX.unset_var "Tried to use unset Database"
        return self.database

    def load_modules():
        """ Check which modules are active and load them"""
        cursor = self.database()
        cursor.execute("select name from modules where active eq true")
        for name in cursor:
            module = __import__(name,globals(),locals(),[Modules])
            callable = module.pass_object()
            temp_thread = threading.Thread(target=callable)
            self.threads.append(temp_thread) 

    def set_quit():
        """ For use by one of the threads. This will tell PokeZX to 
        terminate"""
        self.quit = true

    def main_loop():
        """ Start all the threads, check if it is time to quit. If it is 
        time to quit, delete all the threads (in case the OS or version of 
        Python being used is sloppy)"""
        for thread in self.threads:
            thread.start()
        while not self.quit:
            pass
        for i in range(self.threads.len):
            del self.threads[0]
